package cn.com.callback;

import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import cn.com.kh.KHDBConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// 每天晚上定时清理企微标签数据-为后面全量同步做准备
public class autoQWInitThread implements EliteThreadInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoQWInitThread.class);

    public int doCallBack(EliteBean eliteBean, String content) {
        int runResult = 1;
        log.debug("InitThread Content Info:" + content);
        try {
            // 标记线程执行中避免执行时间较长其他线程也开始调用
            String logSQL = '''Update Elitethread
                                   Set Status = 1,
                                    Expand = Date_Format(Now(), '%Y-%m-%d')
                                 Where Type = 'autoQWInitThread\'
                                   And Content = \'''' + content + '''\'''';
            int logRes = eliteBean.update(logSQL, "dataSource");
            log.debug("标记线程执行中-记录执行DB结果：" + logRes);

            // 开始处理历史数据
            String[] deleteSQL = new String[3];

            if (content == "QW-syncTagUser") {
                deleteSQL[0] = "truncate table kh_qw_sync_tag";
                deleteSQL[1] = "truncate table kh_qw_sync_taguser";
                deleteSQL[2] = "truncate table kh_qw_sync_taguser";

            } else if (content == "QW-syncDp") {
                deleteSQL[0] = "truncate table kh_qw_sync_user";
                deleteSQL[1] = "truncate table kh_qw_sync_user_dp";
                deleteSQL[2] = "truncate table kh_qw_sync_dp";

            } else if (content == "QW-syncExternalUserStatus") {
                deleteSQL[0] = "truncate table kh_qw_sync_externaluser";
                deleteSQL[1] = "truncate table kh_qw_sync_externaluser";
                deleteSQL[2] = "truncate table kh_qw_sync_external_contact";

            }
            int[] deleteSQLRes = eliteBean.updateBatch(deleteSQL, "dataSource");
            log.debug("清理企微历史信息表-影响数量：" + deleteSQLRes);

            // 调用全量同步接口
            String allURL = KHDBConfig.getAPIURL(eliteBean, content);
            try {
                String callRes = Util.doHttpGet(allURL, "UTF-8", 120000, 0);
                log.debug("定时全量同步-调用结果：" + callRes);
            } catch (Exception e) {
                // 保证每天全量异常调用既可
                log.error("定时全量同步-调用异常!", e);
            }

            logSQL = '''Update Elitethread
                                   Set Expand = Date_Format(Now(), '%Y-%m-%d')
                                 Where Type = 'autoQWInitThread\'
                                   And Content = \'''' + content + '''\'''';
            logRes = eliteBean.update(logSQL, "dataSource");
            log.debug("重新同步企微数据-记录执行时间结果：" + logRes);

        } catch (Exception e) {
            log.error("定时清理/重新同步企微数据异常!", e);
            runResult = 0;
        }
        return runResult;
    }

}